package com.juejin.www.controller;

import com.juejin.www.aspect.Log;
import com.juejin.www.aspect.Perm;
import com.juejin.www.model.DTO.PageDTO;
import com.juejin.www.model.DTO.Result;
import com.juejin.www.model.DTO.UserDTO;
import com.juejin.www.model.VO.UserVO;
import com.juejin.www.service.UserService;
import com.juejin.www.utils.AliOSSUtils;
import com.juejin.www.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Jacky
 */
@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO){
        log.info("用户登录：{}",userDTO.getUsername());
        UserDTO u = userService.login(userDTO);

        if(u != null){
            if(u.getStatus()==0){
                //登录失败，用户被封禁
                return Result.error("用户已被封禁，请联系管理员解封！");
            }else {
                //登录成功，生成令牌，下放令牌
                Map<String, Object> claims = new HashMap<>();
                claims.put("id",u.getId());
                claims.put("username",u.getUsername());
                claims.put("name",u.getName());
                claims.put("role",u.getRole());

                String jwt = JwtUtils.generateJwt(claims);
                return Result.success(jwt);
            }
        }

        //登陆失败 ，返回错误信息
        return Result.error("用户名或密码错误");
    }

    @GetMapping("/check/{jwt}")
    public Result checkJwt(@PathVariable String jwt){
        try{
            JwtUtils.parseJWT(jwt);
        }catch (Exception e){
            log.info("解析令牌失败，返回未登录错误信息");
            return Result.error("NOT_LOGIN");
        }
        return Result.success();
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO){
        log.info("用户注册：{}",userDTO.getUsername());
        boolean bol = userService.register(userDTO);
        if(bol){
            return Result.success();
        }else {
            return Result.error("用户名已存在");
        }
    }

    @Perm(permission = "user:read")
    @GetMapping("/user")
    public Result getUsers(@RequestParam Integer currentPage,@RequestParam Integer pageSize){
        log.info("获取用户列表");
        PageDTO<UserVO> users = userService.getUsers(currentPage,pageSize);
        return Result.success(users);
    }

    @Perm(permission = "user:read")
    @GetMapping("/user/{id}")
    public Result getInfo(@PathVariable Integer id,@RequestHeader("token") String jwt){
        Integer uid = null;
        if(jwt!=null){
            try{
                uid = JwtUtils.getIdByJWT(jwt);
            }catch (Exception e){
                uid=null;
            }
        }
        log.info("获取{}号用户信息",id);
        UserVO user = userService.getInfo(id,uid);
        return Result.success(user);
    }

    @Perm(permission = "follow:add")
    @PostMapping("/follow/{beFollowed}")
    public Result followUser(@PathVariable Integer beFollowed,@RequestHeader("token") String jwt){
        Integer follower = JwtUtils.getIdByJWT(jwt);
        log.info("{}号用户关注{}号用户",follower,beFollowed);
        userService.followUser(follower,beFollowed);
        return Result.success();
    }

    @Log
    @Perm(permission = "follow:delete")
    @DeleteMapping("/follow/{beFollowed}")
    public Result cancelFollow(@PathVariable Integer beFollowed,@RequestHeader("token") String jwt){
        Integer follower = JwtUtils.getIdByJWT(jwt);
        log.info("{}号用户取消关注{}号用户",follower,beFollowed);
        userService.cancelFollow(follower,beFollowed);
        return Result.success();
    }
}


